package com.gzx.bi.xxljob;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gzx.bi.modular.current.entity.GzxCurrentId;
import com.gzx.bi.modular.current.service.GzxCurrentIdService;
import com.gzx.bi.modular.goals.monthly.entity.bo.GzxMonthlyGoalsXxlEditBo;
import com.gzx.bi.modular.goals.monthly.service.GzxMonthlyGoalsService;
import com.gzx.bi.modular.repayment.client.entity.GzxRepaymentClient;
import com.gzx.bi.modular.repayment.client.service.GzxRepaymentClientService;
import com.gzx.bi.modular.repayment.subsidiary.entity.GzxRepaymentSubsidiary;
import com.gzx.bi.modular.repayment.subsidiary.service.GzxRepaymentSubsidiaryService;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import vip.xiaonuo.common.tenant.TenantContext;
import vip.xiaonuo.common.util.CommonDateUtil;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author zjt
 * @description
 * @date 2025/1/14 16:03
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RepaymentXxlJob {

    private final GzxMonthlyGoalsService monthlyGoalsService;

    private final GzxCurrentIdService currentIdService;

    private final GzxRepaymentClientService repaymentClientService;

    private final GzxRepaymentSubsidiaryService repaymentSubsidiaryService;


    public void syncRepaymentClient() {
        XxlJobHelper.log("Bi模块--XxlJob定时任务启动---------同步甲方还款数据------>" + CommonDateUtil.getCurrentTimeStr());
        try {
            TenantContext.disableTenantFilter();
            GzxCurrentId currentIdObj = currentIdService.getCurrentIdByType("ClientRepaymentMaxSyncId");
            if (currentIdObj != null) {
                List<GzxRepaymentClient> repaymentClientList = repaymentClientService.selectList(Wrappers.<GzxRepaymentClient>lambdaQuery()
                        .gt(GzxRepaymentClient::getId, currentIdObj.getCurrentId())
                        .isNotNull(GzxRepaymentClient::getRepaymentDate)
                        .isNotNull(GzxRepaymentClient::getBatch));
                //根据项目和批次进行分组
                Map<String, List<GzxRepaymentClient>> repaymentClientMap = repaymentClientList.stream()
                        .collect(Collectors.groupingBy(client -> client.getProjectCode() + "@" + client.getBatch()));
                for (Map.Entry<String, List<GzxRepaymentClient>> repaymentClient : repaymentClientMap.entrySet()) {
                    //累计金额
                    BigDecimal monthlyClientAmount = repaymentClient.getValue().stream().map(GzxRepaymentClient::getRepaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    GzxMonthlyGoalsXxlEditBo monthlyGoalsXxlEditBo = new GzxMonthlyGoalsXxlEditBo();
                    monthlyGoalsXxlEditBo.setMonthlyClientAmount(monthlyClientAmount);
                    monthlyGoalsXxlEditBo.setProjectCode(repaymentClient.getKey().split("@")[0]);
                    monthlyGoalsXxlEditBo.setBatchNumber(repaymentClient.getKey().split("@")[1]);
                    Map<String, BigDecimal> dayMap = repaymentClient.getValue().stream().collect(Collectors.groupingBy(dto -> CommonDateUtil.convertToDate(dto.getRepaymentDate()),
                            Collectors.reducing(BigDecimal.ZERO,
                                    GzxRepaymentClient::getRepaymentAmount,
                                    BigDecimal::add)));
                    monthlyGoalsXxlEditBo.setDayDetail(new TreeMap<>(dayMap));
                    monthlyGoalsService.modifyAchievementAmount(monthlyGoalsXxlEditBo);
                }
                currentIdObj.setCurrentId(repaymentClientList.stream()
                        .mapToLong(GzxRepaymentClient::getId)
                        .max()
                        .orElse(0L));
                currentIdService.updateCurrentId(currentIdObj);
            }
        } catch (Exception e) {
            log.error("同步甲方还款数据出现异常：", e);
        } finally {
            TenantContext.enableTenantFilter();
            TenantContext.clear();
        }
    }

    public void syncRepaymentSubsidiary() {
        XxlJobHelper.log("Bi模块--XxlJob定时任务启动---------同步分公司上报还款数据------>" + CommonDateUtil.getCurrentTimeStr());
        List<GzxRepaymentSubsidiary> repaymentSubsidiaryList = repaymentSubsidiaryService.selectList(Wrappers.<GzxRepaymentSubsidiary>lambdaQuery()
                .ge(GzxRepaymentSubsidiary::getRepaymentDate, CommonDateUtil.getCurrentMonthFirstDay()));
        //根据项目和批次进行分组
        Map<String, List<GzxRepaymentSubsidiary>> repaymentSubsidiaryMap = repaymentSubsidiaryList.stream()
                .collect(Collectors.groupingBy(subsidiary -> subsidiary.getProjectCode() + "@" + subsidiary.getBatch()));
        for (Map.Entry<String, List<GzxRepaymentSubsidiary>> repaymentClient : repaymentSubsidiaryMap.entrySet()) {
            //累计金额
            BigDecimal monthlySubsidiaryAmount = repaymentClient.getValue().stream().map(GzxRepaymentSubsidiary::getRepaymentAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            GzxMonthlyGoalsXxlEditBo monthlyGoalsXxlEditBo = new GzxMonthlyGoalsXxlEditBo();
            monthlyGoalsXxlEditBo.setMonthlySubsidiaryAmount(monthlySubsidiaryAmount);
            monthlyGoalsXxlEditBo.setProjectCode(repaymentClient.getKey().split("@")[0]);
            monthlyGoalsXxlEditBo.setBatchNumber(repaymentClient.getKey().split("@")[1]);
            monthlyGoalsService.modifyAchievementAmount(monthlyGoalsXxlEditBo);
        }
    }
}
